package weiyao.Detector;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Html;
import weiyao.GUI.ScanResultCallback;
import weiyao.Vul.VulnerabilityConfig;

import java.util.List;
import java.util.Map;

public class XssDetector extends BaseDetector {

    @Override
    public void detect(Page page, String baseUrl, ScanResultCallback callback) {
        Html html = page.getHtml();
        List<String> formElements = html.xpath("//form").all();

        for (String formHtml : formElements) {
            Html form = new Html(formHtml);
            String action = form.xpath("//form/@action").get() != null ?
                    form.xpath("//form/@action").get() : baseUrl;
            String method = form.xpath("//form/@method").get() != null ?
                    form.xpath("//form/@method").get() : "GET";

            String formUrl = makeAbsoluteUrl(baseUrl, action);
            Map<String, String> formParams = collectFormParams(form);

            // 使用重载的 testFormParameters 方法（6个参数）
            testFormParameters(formUrl, method, formParams, VulnerabilityConfig.XSS_PAYLOADS,
                    (url, paramName, payload, response) -> {
                        if (isXssVulnerable(response, payload)) {
                            String details = "XSS漏洞!\nURL: " + formUrl +
                                    "\n参数: " + paramName +
                                    "\n载荷: " + payload;  // 添加载荷字段
                            callback.onVulnerabilityFound("XSS", details);
                            return true;
                        }
                        return false;
                    }, callback);
        }
    }
}